//
//  HLTzhoubiantuijianyouhuimerchantTableViewController.m
//  huiliantong
//
//  Created by hlt on 15/9/28.
//  Copyright © 2015年 hlt. All rights reserved.
//

#import "HLTzhoubiantuijianyouhuimerchantTableViewController.h"
#import "HLTShopViewController.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "RecommendCell.h"
#import "SearchViewController.h"
#import "cloudsearchmapViewController.h"
#import <BaiduMapAPI/BMapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface HLTzhoubiantuijianyouhuimerchantTableViewController ()<BMKMapViewDelegate, BMKCloudSearchDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,CLLocationManagerDelegate>
{
    NSMutableArray *_recommendArray;
    NSMutableArray *_MerchantArray;
    NSString *_locationInfoStr;
    NSInteger _KindID;//分类查询ID，默认-1
    NSInteger _offset;
    
    __weak IBOutlet BMKMapView *_mapView;
    BMKCloudSearch* _search;
    BOOL ditu;
}

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) BMKLocationService *locService ;
@property (strong, nonatomic) CLLocation *location;
@property (strong, nonatomic) NSString *lat;
@property (strong, nonatomic) NSString *log;

@end

@implementation HLTzhoubiantuijianyouhuimerchantTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    ditu=YES;
    _MerchantArray = [[NSMutableArray alloc] init];
    _recommendArray = [[NSMutableArray alloc] init];   //商铺数据
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    //取消分割线
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    if (self.shoptye==zoubian) {
        //初始化位置管理器
        [self createLocationManager];
        
    }
    else
    {
        [self initViews];
    }
    
    
    
    
    
}







//创建位置管理器及其相关操作
- (void) createLocationManager
{
    
    //1.创建位置管理器
    self.locationManager = [[CLLocationManager alloc] init];
    //指定委托
    self.locationManager.delegate = self;
    //指定所需精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //距离筛选器
    self.locationManager.distanceFilter = 10;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [self.locationManager requestAlwaysAuthorization];
    }
    
    //启动
    [self.locationManager startUpdatingLocation];
    
    //
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:10.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    
    
    
}



////处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    
    //    CLLocation *newLocation = locations[0];
    //    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    //    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    //
    //    //    CLLocation *newLocation = locations[1];
    //    //    CLLocationCoordinate2D newCoordinate = newLocation.coordinate;
    //    //    NSLog(@"经度：%f,纬度：%f",newCoordinate.longitude,newCoordinate.latitude);
    //
    //    // 计算两个坐标距离
    //    //    float distance = [newLocation distanceFromLocation:oldLocation];
    //    //    NSLog(@"%f",distance);
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    self.lat=  [NSString stringWithFormat:@"%g",  userLocation.location.coordinate.latitude];
    self.log =  [NSString stringWithFormat:@"%g",  userLocation.location.coordinate.longitude];
    
    
    if (ditu) {
        [self initViews];
        ditu=NO;
    }
    
    
    
    
    
}
//定位失败调用
- (void)didFailToLocateUserWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位失败，请检查是否有定位权限!" message:[NSString stringWithFormat:@"%@", error] delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
    [alert show];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setExtraCellLineHidden: (UITableView *)tableView

{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    
    
}

-(void)initViews{
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setUpTableView];
   
    
    
    [self setExtraCellLineHidden:self.tableView];
}



-(void)setUpTableView{
    //添加下拉的动画图片
    //设置下拉刷新回调
    [self.tableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(getFirstPageData)];
    
    //设置普通状态的动画图片
//    NSMutableArray *idleImages = [NSMutableArray array];
//    for (NSUInteger i = 1; i<=60; ++i) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd",i]];
//        [idleImages addObject:image];
//    }
//    [self.tableView.gifHeader setImages:idleImages forState:MJRefreshHeaderStateIdle];
//    
//    //设置即将刷新状态的动画图片
//    NSMutableArray *refreshingImages = [NSMutableArray array];
//    for (NSInteger i = 1; i<=3; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_loading_0%zd",i]];
//        [refreshingImages addObject:image];
//    }
//    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStatePulling];
//    
//    //设置正在刷新是的动画图片
//    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStateRefreshing];
    
    //马上进入刷新状态
    [self.tableView.gifHeader beginRefreshing];
    
    
    //上拉刷新
    [self.tableView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    //隐藏状态文字
    //    self.tableView.footer.stateHidden = YES;
    //设置正在刷新的动画
//    self.tableView.gifFooter.refreshingImages = refreshingImages;
    
    
    
    
}


-(void)getFirstPageData{
    _offset = 0;
    [self refreshData];
}

-(void)refreshData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getMerchantList];
    });
}

-(void)loadMoreData{
    NSLog(@"2222  offset:%zd",_offset);
    _offset = _offset + 10;
    NSLog(@"3333  offset:%zd",_offset);
    [self refreshData];
}


//获取商家列表
-(void)getMerchantList{
    //    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //打开定位功能
    if (self.shoptye==zoubian) {
        
        //开始定位
        [_locService startUserLocationService];
        
    }
    
    
    NSInteger page1=_offset/10;
    //周边商铺列表(x=%@&y=%@&page=0)
    NSString *url;
    if (self.shoptye==zoubian) {
        url=[getzhoubian stringByAppendingFormat:@"&x=%@&y=%@&page=%ld",self.log,self.lat,(long)page1+1];
        [HLTNetWorkingtool getzhoubianlist:url success:^(NSMutableArray *ary) {
            if (_offset<10) {
                [_recommendArray removeAllObjects];
            }
            
            
            for (int i = 0; i < ary.count; i++) {
                HLTZhoubianModel *recommend = [HLTZhoubianModel objectWithKeyValues:ary[i]];
                [_recommendArray addObject:recommend];
            }
            [self.tableView reloadData];
            //刷新指定的section,显示推荐商铺的部分
            //        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
            //        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
        } faliure:^(NSString *error) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
        }];
        
    }
    else if (self.shoptye==tuijiantype)
    {
         url=[recommendlist stringByAppendingFormat:@"&page=%ld",(long)page1];
    }
    else if (self.shoptye==youhuitype)
    {
        url=[youhuishanghu stringByAppendingFormat:@"&page=%ld",(long)page1];
        
    }
    
    if (self.shoptye!=zoubian) {
    NSLog(@"%@",url);
    
    [HLTNetWorkingtool getyouhuilist:url success:^(NSMutableArray *ary) {
        if (_offset<10) {
            [_recommendArray removeAllObjects];
        }
        for (int i = 0; i < ary.count; i++) {
            
                RecommendModel *recommend = [RecommendModel objectWithKeyValues:ary[i]];
                [_recommendArray addObject:recommend];
            
        }
        [self.tableView reloadData];
        //刷新指定的section,显示推荐商铺的部分
        //        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
        //        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    } faliure:^(NSString *error) {
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
    
    }
}





#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _recommendArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellIndentifier = @"recommendcell";
    RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
   
    if (cell == nil) {
        cell = [[RecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    if(_recommendArray.count!=0){
        
        if (self.shoptye==zoubian) {
            HLTZhoubianModel *recommend = _recommendArray[indexPath.row];
            [cell setzhoubianlistData:recommend];
            
        }
        else{
            
            RecommendModel *recommend = _recommendArray[indexPath.row];
            [cell setRecommendData:recommend];
        }
        
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

    
    
    
    
    
}



#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (self.shoptye==zoubian) {
        
        HLTZhoubianModel *recommend = _recommendArray[indexPath.row];
        //                    NSString *shopId = recommend.Shop_id;
        //            NSLog(@"shop id:%@",shopId);
        
        HLTShopViewController *shopvc=[[HLTShopViewController alloc]init];
        //            shopvc.shopcontent=recommend;
        shopvc.zhoubianshopcontent=recommend;
        shopvc.biaozhi=NO;
        shopvc.hidesBottomBarWhenPushed = YES;
        [self.parent.navigationController pushViewController:shopvc animated:YES];

    }
    else{
    
    RecommendModel *recommend = _recommendArray[indexPath.row];
    //                    [recommend objectArray2keyValuesArray]
    //                    NSString *shopId = recommend.Shop_id;
    //            NSLog(@"shop id:%@",shopId);
    
    HLTShopViewController *shopvc=[[HLTShopViewController alloc]init];
    shopvc.shopcontent=recommend;
    shopvc.biaozhi=YES;
    //隐藏tabbar
    shopvc.hidesBottomBarWhenPushed = YES;
    [self.parent.navigationController pushViewController:shopvc animated:YES];
    //                    HLTShopcontentViewController *shopVC = [[HLTShopcontentViewController alloc] init];
    //                    shopVC.imagearray=imagearray;
    //                    shopVC.shopID = shopId;
    //                    shopVC.shopcontent=recommend;
    //                    [self.navigationController pushViewController:shopVC animated:YES];
    
    }
    
    
    
    
    
    
    
    
}




//-(void)viewWillAppear:(BOOL)animated
//{
//    //开始定位
//    [_locService startUserLocationService];
//    
//    
//}


//视图消失之后调用的
- (void)viewDidDisappear:(BOOL)animated
{
    //停止定位操作
    [_locService stopUserLocationService];
    
}



@end
